<?php
class ipbanned
{
	private $table;
	private $db;
	public $pages;
	
	function ipbanned()
	{
		global $db;
		$this->table = DB_PRE.'ipbanned';
		$this->db=&$db;
	}
	
	/**
	 * 获得ip列表
	 *
	 * @param int $page
	 * @param int $pagesize
	 * @param varchar $ip
	 * @return array
	 */
	function get_ips($page,$pagesize,$ip)
	{
		$start = ($page - 1) * $pagesize;
		if(!empty($ip))
		{
			$ip_pos = explode('.', $ip);
			$tmp = array();
			foreach ($ip_pos as $pos)
			{
				$tmp[] = is_numeric($pos) ? "($pos|\\*)" : '[0-9*]+';
			}
			$ip = implode('.', $tmp);
			$where = " where ip REGEXP ?";
			$ip = '^'.$ip.'$';
		}
		else 
		{
			$where = ' where 1=1';
		}
        $where .= " and status=".STATUS_NORMAL;
		$this->db->prepare('select count(*) as nums from '.$this->table.$where);
		if(!empty($ip))
		{
			$this->db->set_string($ip);
		}
		$c_res = $this->db->execute(true);
		$this->db->prepare('select * from '.$this->table . $where . ' order by expires asc limit ?,?');
		if(!empty($ip))
		{
			$this->db->set_string($ip);
		}
		$this->db->set_int($start);
		$this->db->set_int($pagesize);
		$res = $this->db->execute();
		$cout = $c_res['nums'];
		$this->pages = pages($cout,$page,$pagesize);
		return $res;
	}
	
	/**
	 * 添加ip
	 *
	 * @param varchar $ip
	 * @param int $expires
	 * @return bool
	 */
	function add_ip($ip,$expires='')
	{
		$expires = empty($expires) ? 0 : strtotime($expires);
		$params = array(
			'ip'		=>	$ip,
			'expires'	=>	$expires
		);
		$res = $this->db->insert($this->table, $params);
		return $res;
	}
	
	/**
	 * 删除单个ip
	 *
	 * @param varchar $ip
	 * @return bool
	 */
	function delete_ip($ip)
	{
        return $this->db->fake_delete($this->table, array('ip'=>$ip));
	}
	
	/**
	 * 删除过期ip
	 *
	 * @return bool
	 */
	function delete_expires()
	{
		$this->db->prepare('update '.$this->table.' set status=? where expires<? and expires>0');
		$this->db->set_int(STATUS_DEL);
		$this->db->set_int(time());
		$res = $this->db->execute();
		return $res;
	}
}
?>